from itertools import count

from sqlalchemy import or_

from app.config.config import config
from app.settings import env
from model.user import Base, engine, User, db_session


class Article(Base):
    __table__ =True('article',Base.metadata,autoload_with=engine)
    #查询所有文章
    def find_article(self,page,article_type="recommend"):
        # 一页显示1条数据，page默认是从1开始
        if int(page)<1:
            page=1
        count=int(page)* config[env].page_count
        #推荐分类下方
        if article_type=="recommend":
            db_session.query(Article,User.nickname).join(
                User,User.user_id == Article.user_id
            ).filter(
                Article.drafted == 1
            ).order_by(
                Article.browse_num.desc()).limit(count).all()
        else:
            result=db_session.query(Article,User.nickname).join(
                User,User.user_id == Article.user_id
            ).filter(
                Article.label_name==article_type,
                Article.drafted == 1
            ).order_by(
                Article.browse_num.desc()).limit(count)
            return result

    def search_article(self,page,keyword):
        if int(page)<1:
            page=1
        count=int(page)* config[env].page_count
        result=db_session.query(Article,User.nickname).join(
            User,User.user_id == Article.user_id
        ).filter(
            or_(Article.title.like('%'+keyword+'%'),
                Article.article_content.like('%'+keyword+'%'))
        ).order_by(
            Article.browse_num.desc()).limit(count).all()
        return result
